package com.edu.juc.completableFuture;

import java.util.concurrent.*;

public class CompletableFutureTest2 {
    public static void main(String[] args) {

        ExecutorService executor = Executors.newFixedThreadPool(10);

        try {
            CompletableFuture.supplyAsync(() -> {
                System.out.println(Thread.currentThread().getName() + "----come in.");
                int result = ThreadLocalRandom.current().nextInt(10);
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                System.out.println("---after 1 seconds, result:" + result);
                return result;
            }, executor).whenComplete((v, e) -> {
                if (e == null) {
                    System.out.println("----计算结果：" + v);
                }
            }).exceptionally(e -> {
                e.printStackTrace();
                return null;
            });

            System.out.println("----main continue...");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            executor.shutdown();
        }

        // 主线程不要立刻结束，否则CompletableFuture默认使用的线程池会立刻关闭
//        try {
//            TimeUnit.SECONDS.sleep(3);
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
    }
}
